import { messages, queryCurrencyPrecision, dealListTag } from "share/common";
import React from 'react'
import ExportModal from 'components/template/export-modal/export-modal';
import {connect} from 'react-redux'
import { message, Badge, Popover, Button, Alert, Modal, Tabs, Row, Col, Checkbox, Select, Spin, Tag } from 'antd'
const TabPane = Tabs.TabPane;
const Option = Select.Option;
import moment from 'moment'
import config from 'config'
import menuRoute from 'routes/menuRoute'
import constants from 'share/constants'
import SearchArea from 'components/search-area'
import financeViewService from 'containers/financial-management/expense-view/expense-view.service'
import borrowService from 'containers/loan-billing/borrow-and-return.service'
import CostCenterSearchForm from 'components/template/cost-center-search-form/cost-center-search-form'
import ResizeTable from 'components/resize-table'
import 'styles/financial-management/expense-view/expense-view.scss'
import BatchDownload from './batch-download'

class FinanceView extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      batchBtnLoading: false,
      batchListLoading: false,
      modalVisible: false,
      searchForm: [
        {
          type: 'searcher',
          id: 'formOIDs',
          label: messages('financial-management.key176'/*表单类型*/),
          listType: 'authority_form',
          descriptionKey: 'companyName',
          labelKey: 'formName',
          valueKey: 'formOID',
          listExtraParams: {formType: 1002}
        },
        {
          type: 'combobox', id: 'userOID', label: messages('financial-management.key123'/*申请人姓名/工号*/),
          placeholder: messages('common.please.enter') + messages('financial-management.key123'/*申请人姓名/工号*/),
          options: [], searchUrl: `${config.baseUrl}/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`, method: 'get', searchKey: 'keyword',
          labelKey: 'fullName', valueKey: 'userOID',
          renderOption: option => (`${option.employeeID}-${option.fullName}${(option.status !== 1001 ? (
            `（${option.status === 1002 ? messages('financial-management.key622')/*待离职员工*/ : messages('financial-management.key623')/*离职员工*/}）`
          ) : '')}`)
        },
        {
          type: 'combobox', id: 'businessCode', label: messages('financial-management.key234'/*单据ID*/),
          placeholder: messages('common.please.enter') + messages('financial-management.key624')/*父单/子单ID/报销单ID*/,
          options: [], searchUrl: `${config.baseUrl}/api/expense/report/loanApplication/search`, method: 'get',
          searchKey: 'keyword', getParams: {entityType: '1002'}, labelKey: '_self', valueKey: '_self'
        },
        {
          type: 'list', id: 'departmentOIDs', label: messages('financial-management.key195'/*部门*/),
          listType: 'department', labelKey: 'name', valueKey: 'departmentOid'
        },
        {
          type: 'items', id: 'dateRange', items: [
            {type: 'date', id: 'beginDate', label: messages('financial-management.key126'/*提交日期从*/), defaultValue: moment().subtract(1, 'month')},
            {type: 'date', id: 'endDate', label: messages('financial-management.key127'/*提交日期至*/), defaultValue: moment()}
          ]
        },
        {
          type: 'items', id: 'approvalDateRange', items: [
            {type: 'date', id: 'approvalStartDate', label: messages('financial-management.key193'/*审批日期从*/)},
            {type: 'date', id: 'approvalEndDate', label: messages('financial-management.key194'/*审批日期至*/)}
          ]
        },
        {
          type: 'items', id: 'auditedApprovalDateRange', items: [
            {type: 'date', id: 'auditedApprovalStartDate', label: messages('financial-management.key236'/*审核日期从*/)},
            {type: 'date', id: 'auditedApprovalEndDate', label: messages('financial-management.key237'/*审核日期至*/)}
          ]
        },
        {
          type: 'multiple', id: 'legalEntity', label: messages('financial-management.key128'/*法人实体*/), options: [],
          getUrl: `${config.baseUrl}/api/finance/role/legalEntity/query?page=0&size=100`, method: 'get',
          labelKey: 'entityName', valueKey: 'companyReceiptedOID', listKey: "rows"
        },
        {
          type: 'select', id: 'autoAudit', label: messages('financial-management.key238'/*自动审核通过*/),
          options: [
            {label: messages('financial-management.key139'/*全部*/), value: null},
            {label: messages('common.yes')/*是*/, value: true},
            {label: messages('common.no')/*否*/, value: false}
          ]
        },
        {
          type: 'multiple', id: 'labelIds', label: messages('financial-management.key574')/*单据标签*/, options: [],
          getUrl: `${config.baseUrl}/api/expense/labels?labelCategory=1`, method: 'get', labelKey: 'name', valueKey: 'id'
        },
        {
          type: 'items', id: 'financeReceiptDateRange', items: [
            {type: 'date', id: 'financeReceiveStartDate', label: messages('financial-management.key797')/*收单日期从*/},
            {type: 'date', id: 'financeReceiveEndDate', label: messages('financial-management.key798')/*收单日期至*/}
          ]
        },
        {
          type: 'combobox', id: 'reimbursementBatchId', label: messages('financial-management.key768')/*付款批次号*/,
          placeholder: messages('common.please.enter') + messages('financial-management.key768')/*付款批次号*/,
          options: [],
          searchUrl: `${config.baseUrl}/api/reimbursement/batch/query/byBatchName?batchType=3001&roleType=TENANT`,
          method: 'get',
          searchKey: 'batchName',
          labelKey: 'reimbursementBatchName',
          valueKey: 'id'
        },
        {
          type: 'checkbox', id: 'status', label: messages('common.column.status'/*状态*/), colSpan: 24, options: [
            {label: messages('financial-management.key120'/*审批中*/), value: 'submitted'},
            {label: messages('financial-management.key121'/*已通过*/), value: 'approval_pass'},
            {label: messages('financial-management.key122'/*已驳回*/), value: 'approval_reject'},
            {label: messages('financial-management.key229'/*审核通过*/), value: 'audit_pass'},
            {label: messages('financial-management.key227'/*审核驳回*/), value: 'audit_reject'},
            {label: messages('financial-management.key232'/*付款中*/), value: 'payment_in_process'},
            {label: messages('financial-management.key174'/*已付款*/), value: 'finance_loan'},
          ]
        }
      ],
      searchParams: {},
      columns: [
        {title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48, render: (text, record, index) =>
            (this.state.page * this.state.pageSize + index + 1)},
        {title: messages('financial-management.key130'/*工号*/), dataIndex: 'employeeID'},
        {title: messages('financial-management.key131'/*申请人*/), dataIndex: 'applicant'},
        {title: messages('financial-management.key132'/*提交日期*/), dataIndex: 'lastSubmittedDate', width: 95,
          render: (date, record) => moment(date || record.createDate).format('YYYY-MM-DD'), sorter: true},
        {title: messages('financial-management.key133'/*单据类型*/), dataIndex: 'formName', render: value =>
            <Popover content={value}>{value}</Popover>, sorter: true},
        {title: messages('financial-management.key134'/*单号*/), dataIndex: 'businessCode', render: (value, record) => (
            <Popover content={record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}>
              {record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}
            </Popover>
          ), sorter: true},
        {title: messages('financial-management.key136'/*总金额*/), dataIndex: 'totalAmount', align: "right",
          render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode)), sorter: true},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: 'currencyCode', width: 48},
        {title: messages('financial-management.key170'/*凭证编号*/), dataIndex: 'origDocumentSequence', width: '7%',
          render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : '-'},
        {title: messages('financial-management.key799')/*批量打印批次号*/, dataIndex: 'expenseReportBatchId',
          render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : '-'},
        {title: messages('common.column.status'), dataIndex: 'status', width: props.language.code === 'zh_cn' ? '8%' : '13%',
          render: (value, record) => (
            <Tag color={
              constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'color') ||
              constants.getTextByValue(String(value), 'documentStatus', 'color')
            } >
              {
                constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
                constants.getTextByValue(String(value), 'documentStatus')
              }
            </Tag>
          )
        },
        {title: messages('common.operation'), dataIndex: 'operation', width: 50,
          render: (value, record) =>
            <a onClick={event => this.print(record, event)}>{messages('financial-management.key137'/*打印*/)}</a>
        }
      ],
      data: [],
      pagination: {
        total: 0,
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100', '200'],
        defaultPageSize: 10
      },
      sort: '',
      pageSize: 10,
      page: 0,
      existsExpenseReportBatchId: true, //批次号是否存在
      batchSize: 100, //打印批次数量
      batchNumOptionsFetching: false,
      batchNumOptions: [],
      expenseReportBatchId: undefined,
      expenseDetailView: menuRoute.getRouteItem('expense-report-detail-view', 'key'),
      loanDetailView: menuRoute.getRouteItem('loan-detail-view', 'key'),
    }
  }

  componentDidMount(){
    this.initUX()
  };

  initUX = () => {
    let { searchForm, pagination } = this.state;
    let params = [
      {factorCode:"COMPANY", factorValue: this.props.user.companyId},
      {factorCode:"SET_OF_BOOKS", factorValue: this.props.company.setOfBooksId}
    ];
    this.setState({ loading: true });
    financeViewService.searchPrintFree(this.props.user.tenantId, params).then(res => {
      //fix bug25401 【取消支付】搜索条件需要读取租户级profile
      if (this.props.profile['finance.payment.cancel']) {
        searchForm.map(item => {
          if (item.id === 'status') {
            item.options.push({label: messages('financial-management.key571')/*取消支付*/, value: 'pay_cancel'})
          }
        })
      }
      pagination.total = 0;
      pagination.current = 1;
      this.setState({
        searchForm,
        searchParams: {},
        pagination,
        sort: ''
      },() => {
        this.getList(true)
      });
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('financial-management.key566')/*系统异常*/);
    });
  };

  //获取列表数据
  getList = (firstRequest) => {
    const { page, pageSize, searchParams, sort,pagination } = this.state;
    if (firstRequest) {
      searchParams.beginDate = moment().subtract(1, 'month').format('YYYY-MM-DD 00:00:00');
      searchParams.endDate = moment().format('YYYY-MM-DD 23:59:59');
    }
    searchParams.entityType = 1002;
    this.setState({ loading: true });
    if(sort) {
      searchParams.sorts = {
        property: sort.split(',')[0],
        direction: sort.split(',')[1]
      };
    }
    if (pagination.total !== 0) {
      searchParams.total = pagination.total;
    }
    financeViewService.getFinanceViewList(page, pageSize, searchParams).then(res => {
      if (res.status === 200) {
        this.setState({
          loading: false,
          data: res.data,
          pagination: {
            total: Number(res.headers['x-total-count']),
            pageSize: this.state.pageSize
          }
        })
      }
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  getBatchList = () => {
    const { batchPage, pageSize } = this.state;
    let params = {
      page: batchPage,
      size: pageSize
    };
    this.setState({ batchListLoading: true });
    financeViewService.getBatchList(params).then(res => {
      this.setState({
        batchListLoading: false,
        batchData: res.data,
        batchPagination: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager
        }
      })
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.batchPage)
      this.setState({
        batchPage: page - 1
      }, () => {
        this.getBatchList();
      })
  };

  search = (result) => {
    let { searchParams } = this.state;
    result.beginDate && (result.beginDate = moment(result.beginDate).format('YYYY-MM-DD 00:00:00'));
    result.endDate && (result.endDate = moment(result.endDate).format('YYYY-MM-DD 23:59:59'));
    result.approvalStartDate && (result.approvalStartDate = moment(result.approvalStartDate).format('YYYY-MM-DD 00:00:00'));
    result.approvalEndDate && (result.approvalEndDate = moment(result.approvalEndDate).format('YYYY-MM-DD 23:59:59'));
    result.auditedApprovalStartDate && (result.auditedApprovalStartDate = moment(result.auditedApprovalStartDate).format('YYYY-MM-DD 00:00:00'));
    result.auditedApprovalEndDate && (result.auditedApprovalEndDate = moment(result.auditedApprovalEndDate).format('YYYY-MM-DD 23:59:59'));
    result.financeReceiveStartDate && (result.financeReceiveStartDate = moment(result.financeReceiveStartDate).format('YYYY-MM-DD 00:00:00'));
    result.financeReceiveEndDate && (result.financeReceiveEndDate = moment(result.financeReceiveEndDate).format('YYYY-MM-DD 23:59:59'));
    result.printFree === 'null' && (delete result.printFree);
    result.searchCorporations = result.legalEntity ? result.legalEntity : [];
    result.searchCostCenterCommands = searchParams.searchCostCenterCommands;
    result.existsExpenseReportBatchId = this.state.existsExpenseReportBatchId;
    result.expenseReportBatchId = this.state.expenseReportBatchId;
    result.reimbursementBatchIdLable && (result.reimbursementBatchName = result.reimbursementBatchIdLable);
    if (result.existsExpenseReportBatchId && !result.expenseReportBatchId) { //没有选择批次号时，不要传参数existsExpenseReportBatchId
      delete result.existsExpenseReportBatchId
    }
    this.setState({
      searchParams: result,
      page: 0,
      pagination: {
        total: 0,
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100', '200'],
      }
    }, ()=>{
      this.getList();
    })
  };

  clear = () => {
    this.handleSearchData();
    this.setState({ searchParams: {} })
  };

  handleSearchData = () => {
    let searchForm = this.state.searchForm;
    let dateRange = searchForm.filter(item => item.id === 'dateRange')[0];
    dateRange.items[0].defaultValue = null;
    dateRange.items[1].defaultValue = null;
    this.setState({ searchForm })
  };

  handleRowClick = (record) => {
    if (record.entityType === 1002) {
      window.open(this.state.expenseDetailView.url.replace(':expenseReportOID', record.entityOID))
    } else {
      window.open(this.state.loanDetailView.url.replace(':formOID', record.formOID).replace(':loanBillOID', record.entityOID))
    }
  };

  print = (record,event) => {
    event.preventDefault();
    event.stopPropagation();
    event.cancelBubble = true;
    if (record.entityType === 1002) {
      financeViewService.printExpenseReport(record.entityOID).then(res => {
        window.open(res.data.fileURL, '_blank');
      })
    } else {
      borrowService.printLoanApplication(record.entityOID).then(res => {
        window.open(res.data.link, '_blank')
      })
    }
  };

  //表格分页、排序、筛选变化时触发
  handleTableChange = (pagination, filters, sorter) => {
    let page = pagination.current;
    let pageSize = pagination.pageSize;
    let sort = '';
    if(sorter.order){
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    this.setState({
      page: page - 1,
      sort,
      pageSize
    }, ()=>{
      this.getList();
    })
  };

  //修改成本中心
  changeCostCenter = (value) => {
    const { searchParams } = this.state;
    searchParams.searchCostCenterCommands = value;
    this.setState({searchParams})
  };

  //获取批次号options
  getBatchNumOptions = (key) => {
    if (key.length >= 4 && key.length <= 17) {
      this.setState({ batchNumOptionsFetching: true });
      financeViewService.getBatchNumList(key).then(res => {
        this.setState({
          batchNumOptionsFetching: false,
          batchNumOptions: res.data || []
        })
      }).catch(() => {
        this.setState({
          batchNumOptionsFetching: false,
          batchNumOptions: []
        })
      })
    }
  };

  //报销单 - 生成批次
  toGenerateExpenseBatch = () => {
    this.setState({ batchBtnLoading: true });
    let params = this.state.searchParams;
    params.batchSize = this.state.batchSize;
    financeViewService.createBatch(params).then(res => {
      this.setState({ batchBtnLoading: false });
      if (res.data.total) {
        this.setState({ modalVisible: false });
        message.success(messages('financial-management.key601')/*批次生成成功*/);
        this.getList()
      } else {
        message.error(messages('financial-management.key602')/*批次号为空的单据才可生成批次！*/)
      }
    }).catch(() => {
      this.setState({ batchBtnLoading: false })
    })
  };

  /**
   * 设置【生成pdf】【下载】【删除】按钮的loading状态
   * @param id: 批次号id
   * @param type: pdfLoading downloadLoading deleteLoading
   * @param isLoading: true false
   */
  setBtnLoading = (id, type, isLoading) => {
    let batchData = this.state.batchData;
    batchData.map(item => {
      if (item.expenseReportBatchId === id) {
        item[type] = isLoading
      }
    });
    this.setState({ batchData })
  };

  //生成pdf
  generatePDF = (id) => {
    this.setBtnLoading(id, 'pdfLoading', true);
    financeViewService.generatePDF(id).then(() => {
      this.getBatchList()
    }).catch(() => {
      this.setBtnLoading(id, 'pdfLoading', false)
    })
  };

  //下载批次
  downloadBatch = (id) => {
    this.setBtnLoading(id, 'downloadLoading', true);
    financeViewService.downloadBatch(id).then(res => {
      this.setBtnLoading(id, 'downloadLoading', false);
      window.open(res.data.fileURL)
    }).catch(() => {
      this.setBtnLoading(id, 'downloadLoading', false)
    })
  };

  //删除批次
  handleDeleteBatch = (id) => {
    this.setBtnLoading(id, 'deleteLoading', true);
    financeViewService.deleteBatch(id).then(() => {
      message.success(messages('common.delete.success', {name: ""})/*删除成功*/);
      this.setBtnLoading(id, 'deleteLoading', false);
      this.getBatchList()
    }).catch(() => {
      this.setBtnLoading(id, 'deleteLoading', false)
    })
  };

  render() {
    const { loading, batchBtnLoading, modalVisible, searchForm, columns, data,
      pagination, searchParams, existsExpenseReportBatchId, batchSize, batchNumOptions,
      batchNumOptionsFetching, expenseReportBatchId } = this.state;
    let extraFields = [
      <div>
        <div style={{lineHeight: '28px'}}>
          {messages('financial-management.key145'/*成本中心*/)}
        </div>
        <CostCenterSearchForm title={messages('financial-management.key145'/*成本中心*/)}
                              value={searchParams.searchCostCenterCommands}
                              onChange={this.changeCostCenter}/>
      </div>,
      <div className="search-batch-num">
        <div style={{lineHeight: '28px'}}> {messages('financial-management.key799')/*批量打印批次号*/}
        </div>
        <Row>
          <Col span={16}>
            <Select showSearch
                    allowClear
                    placeholder={messages('financial-management.key603')/*请输入四位以上批次号搜索*/}
                    notFoundContent={batchNumOptionsFetching ? <Spin size="small"/> : messages('common.unmatched'/*无匹配结果*/)}
                    disabled={!existsExpenseReportBatchId}
                    value={expenseReportBatchId}
                    onSearch={this.getBatchNumOptions}
                    onSelect={value => this.setState({expenseReportBatchId: value})}
                    onChange={value => !value && this.setState({expenseReportBatchId: undefined})}
            >
              {batchNumOptions.map(option => {
                return <Option key={option}>{option}</Option>
              })}
            </Select>
          </Col>
          <Col span={7} offset={1} className="null-batch-num">
            <Checkbox onChange={e => this.setState({existsExpenseReportBatchId: !e.target.checked, expenseReportBatchId: undefined})}/> {messages('financial-management.key604')/*批次号为空*/}
          </Col>
        </Row>
      </div>
    ];
    let noticeMessage = messages('financial-management.key620')/*列表中<span class='color-blue'>批量打印批次号为空</span>的数据将会生成批次。*/;
    return (
      <div className="expense-view full-height-page">
        <Tabs type="card">
          <TabPane tab={messages('financial-management.key605')/*报销单查看*/} key="1">
            <SearchArea searchForm={searchForm}
                        submitHandle={this.search}
                        isReturnLabel
                        clearHandle={this.clear}
                        extraFieldsIndex={9}
                        extraFields={extraFields}/>
            <div className="table-header">
              <div className="table-header-buttons">
                <ExportModal
                  type={"btn"}
                  btnType="primary"
                  exportTitle={messages('financial-management.key146'/*导出搜索数据*/)}
                  exportType="BILL_CHECK"
                  exportCondition={{
                    billCheckSearchCommand: this.state.searchParams
                  }}
                  exportCommand={'EXP_OR_LOANBILL'}/>
                <Button onClick={() => this.setState({modalVisible: true})}>{messages('financial-management.key33')/*生成批次*/}</Button>
              </div>
              <div className="table-header-title">{messages('common.total',{total: pagination.total || 0}/*共多少条数据*/)}</div>
            </div>
            <Alert className="notice" type="info" showIcon
                   message={<div dangerouslySetInnerHTML={{__html: noticeMessage}} />} />
            <ResizeTable
              rowKey={record => record.entityOID}
              columns={columns}
              dataSource={data}
              loading={loading}
              pagination={pagination}
              onChange={this.handleTableChange}
              onRow={record => ({onClick: () => {this.handleRowClick(record)}})}
              expandedRowRender={dealListTag}
              rowClassName={record => record.printFree ? '' : 'row-expand-display-none'}
              bordered
              size="middle"
            />
          </TabPane>
          <TabPane tab={messages('financial-management.key607')/*批次下载*/} key="2">
            <BatchDownload />
          </TabPane>
        </Tabs>

        <div className="modal-container"/>
        <Modal
          visible={modalVisible}
          title={messages('financial-management.key33')/*生成批次*/}
          getContainer={() => document.getElementsByClassName('modal-container')[0]}
          footer={[
            <Button key="cancel" onClick={() => this.setState({ modalVisible: false })}>
              {messages('common.cancel')}
            </Button>,
            <Button
              key="ok"
              type="primary"
              loading={batchBtnLoading}
              onClick={this.toGenerateExpenseBatch}
            >
              {messages('common.ok')}
            </Button>,
          ]}
          onCancel={() => this.setState({ modalVisible: false })}
        >
          <Alert
            type="info"
            showIcon
            message={
              messages('financial-management.key608')
              /*当批次中数量过大可能导致打印失败，请根据您的机器性能进行选择。推荐：100条/批*/
            }
          />
          <div className="set-batch-size">
            {messages('financial-management.key31')/*设置打印批次*/}
            :
            <Select value={batchSize} onChange={value => this.setState({ batchSize: value })}>
              <Option key={100}>100</Option>
              <Option key={200}>200</Option>
              <Option key={500}>500</Option>
            </Select>
            /
            {messages('financial-management.key32')/*批*/}
          </div>
        </Modal>
      </div>
    )
  }
}

FinanceView.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language,
    profile: state.login.profile
  }
}

export default connect(mapStateToProps)(FinanceView);
